package com.cray.intelligenthydrologyback.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author Emil
 */
@Configuration
public class WebClientConfig {

    @Autowired
    private GlobalConfig config;

    public static String TOKEN = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjY3ZmZiYTNmLTY5N2YtNDMwYi05ZTBjLWY1MDAzOWUxMjc0YyJ9.lon7VGijwQJtSIbCehvg61x9Ch1CrdIkTE2TUJHDN91rCbT0H9BYttbuLN2CNpGDreaFzQerEFdT4q6poh7gtQ";

    @Bean
    public WebClient.Builder webClientBuilder() {
        return WebClient.builder()
                .baseUrl(config.getUrl()) // 默认 Base URL
                .defaultHeader("Accept", "application/json") // 默认头部
                .exchangeStrategies(ExchangeStrategies.builder()
                        .codecs(configurer ->
                                configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024)) // 增大内存限制
                        .build())
                .filter((request, next) -> { // 请求和响应日志拦截器
                    System.out.println("Request: " + request.method() + " " + request.url());
                    request.headers().forEach((name, values) ->
                            values.forEach(value -> System.out.println(name + ": " + value))
                    );

                    return next.exchange(request)
                            .flatMap(response -> {
                                System.out.println("Response Status: " + response.statusCode());
                                response.headers().asHttpHeaders().forEach((name, values) ->
                                        values.forEach(value -> System.out.println(name + ": " + value))
                                );

                                // 获取和打印响应体
                                return response.bodyToMono(String.class).flatMap(body -> {
                                    System.out.println("Response Body: " + body);
                                    // 可以返回修改后的响应
                                    return Mono.just(response.mutate().body(body).build());
                                });
                            });
                });
    }
}
